package com.agadmin.response;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Field;


public class GlobalResponseBodyHandle implements HandlerMethodReturnValueHandler,
        AsyncHandlerMethodReturnValueHandler {


    @Override
    public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
        return supportsReturnType(returnType);
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getParameterType() != GlobalResponse.class
                && !ObjectUtils.isEmpty(returnType.getAnnotatedElement().
                getAnnotation(GlobalResponseBody.class));
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        mavContainer.setRequestHandled(true);
        Class<?> model = returnValue.getClass();
        int code = 200;
        String msg = "successful";
        for (Field field : model.getDeclaredFields()) {
            String name = field.getName();
            try {
                if (name.equals("code")) {
                    field.setAccessible(true);
                    code = Integer.parseInt(field.get(returnValue).toString());
                } else if (name.equals("error")) {
                    field.setAccessible(true);
                    msg = field.get(returnValue).toString();
                }
            } catch (Exception e) {
                code = 1009;
                msg = e.getMessage();
                break;
            }
        }

        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        GlobalResponse<Object> res = new GlobalResponse();
        response.setContentType("application/json;charset=utf-8");
        res.setCode(code);
        res.setError(msg);
        if (code == 200) {
            response.getWriter().write(JSON.toJSONString(returnValue));
        } else {
            response.getWriter().write(JSON.toJSONString(res));
        }


    }
}
